package net.pulseproject.router.modules.misc;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import net.pulseproject.commons.midi.Receivable;
import net.pulseproject.commons.midi.Transmitable;
import net.pulseproject.router.modules.Module;
import net.pulseproject.router.modules.useable.MidiTransmitterModule;

public class RoutingTable {
	
	private static final Log LOG = LogFactory.getLog(RoutingTable.class);
	
	private final Collection<MidiTransmitterModule> transmitterModules;

	public RoutingTable(final Collection<MidiTransmitterModule> transmitterModules) {
		if(transmitterModules == null) { throw new IllegalArgumentException("transmitterModules == null"); }
		this.transmitterModules =
			Collections.unmodifiableList(new ArrayList<MidiTransmitterModule>(transmitterModules));
	}

	public final Collection<MidiTransmitterModule> getTransmitterModules() {
		return this.transmitterModules;
	}

	public void destroyAllModules() {
		LOG.debug("destroyAllModules()");
		for (MidiTransmitterModule rootModule : this.transmitterModules) {
			rootModule.destroy();
			this.maybeDestroy(rootModule.getOutgoingModules());
		}
	}

	private void maybeDestroy(Collection<Receivable> outgoingModules) {
		for (Receivable receivable : outgoingModules) {
			if(receivable instanceof Module) {
				LOG.trace("maybeDestroy() ... receivable=" + receivable);
				((Module) receivable).destroy();
			}
			if(receivable instanceof Transmitable) {
				this.maybeDestroy(((Transmitable) receivable).getOutgoingModules());
			}
		}
	}
	
}
